<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Jobposition;
use App\Models\CategoryModel;
use App\Models\CompanyModel;
use App\Models\JobPositionCheckModel;
use App\Models\JobpositionModel;
use App\Models\PlatformModel;
use App\Models\PlazaModel;
use App\Services\Im\WechatService;
use App\Services\Jobposition\JobpositionService;
use App\Services\Tenancy\Tenancy;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Table;
use ErrorException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use SuperEggs\DcatDistpicker\DcatDistpickerHelper;
use Dcat\Admin\Http\JsonResponse;

class JobpositionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Jobposition(['company', 'categories', 'statistics', 'platforms']), function (Grid $grid) {
            $category_id = request('_selector.categories_id');
            if ($category_id > 0) {
                $grid->model()->orderBy(JobpositionService::getSortKey($category_id))->orderBy('id');
            } else {
                $grid->model()->orderByDesc('id');
            }
            $grid->column('id');
            $grid->column('platforms', '发布平台')->display(function ($value) {
                return implode('|', Arr::pluck($value ? $value->toArray() : [], 'name'));
            });
            $grid->column('company.company_name', '公司')->display(function ($value) {
                return empty($value) ? $this['company']->contact_person_name : $value;
            })->limit(10);
            // $grid->column('company.company_name', '公司')->display(function () {
            //     $value =$this->company;
            //     return $value->cur_type == CompanyModel::TYPE_PERSON ? $value->contact_person_name : $value->company_name;
            // })->limit(10);
            $grid->column('company.contact_person_name', '联系人')->limit(10);
            $grid->column('position_name')->limit(10);
            if ($category_id > 0) {
                $grid->column(JobpositionService::getSortKey($category_id), '排序')->editable(true);
            } else {
                $grid->column('categories', '分类')->display(function ($value) {
                    return implode('|', Arr::pluck($value->toArray(), 'name'));
                });
            }
            $grid->column('region', '招聘区域')->display(function () {
                if (!$this->region_region) {
                    return '全国';
                }
                return DcatDistpickerHelper::getAreaName($this->region_province) . DcatDistpickerHelper::getAreaName($this->region_city) . DcatDistpickerHelper::getAreaName($this->region_region);
            });
            $grid->column('vr_status', '上线状态')->display(function ($value) {
                $status = [0 => '下线', 1 => '上线'][$this->vrStatus()] ?? '';
                $color = [0 => 'red', 1 => '#19b60d'][$this->vrStatus()] ?? '';
                return "<span style='color: {$color}'>{$status}</span>";
            });
            $grid->column('statistics.pv', '浏览量')->display(function ($value) {
                return $value ?? 0;
            });
            $grid->column('statistics.uv', '浏览人数')->display(function ($value) {
                return $value ?? 0;
            });
            $grid->column('expected_num', '最大报名人数');
            $grid->column('recruit_num', '报名人数');
            $grid->column('content', '联系方式')
                ->display('查看') // 设置按钮名称
                ->modal(function ($modal) {
                    // 设置弹窗标题
                    $modal->title('联系方式');

                    // 自定义图标
                    $modal->icon('feather icon-aperture');
                    //                    return "<div style='padding:10px 10px 0'>暂无联系方式</div>";
                    $card = new Table();
                    $rows = [];
                    $header = [];
                    if ($this->contact_type == JobpositionModel::CONTACT_MOBILE) {
                        $header = ['手机号', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactPhone as $item) {
                            $rows[] = [
                                $item->phone_number,
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_QQ) {
                        $header = ['QQ号码', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactQq as $item) {
                            $rows[] = [
                                $item->qq_number,
                                "<image src='$item->qq_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_WECHAT) {
                        $header = ['微信号', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactWechat as $item) {
                            $rows[] = [
                                $item->wechat_number,
                                "<image src='$item->wechat_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_DINGTALK) {
                        $header = ['钉钉号', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactDingtalk as $item) {
                            $rows[] = [
                                $item->dingtalk_number,
                                "<image src='$item->dingtalk_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($header) {
                        $card->setHeaders($header)->setRows($rows);
                        return "<div style='padding:10px 10px 0'>$card</div>";
                    } else {
                        return "<div style='padding:10px 10px 0'>暂无联系方式</div>";
                    }
                });
            $grid->column('salary')->display(function ($value) {
                return $value . '/' . JobpositionModel::SALARY_TYPE_LIST[$this->salary_type] ?? '';
            });
            $grid->column('gender_requirement')->using(JobpositionModel::GENDER_LIST);
            $grid->column('age', '年龄')->display(function ($value) {
                return ageInfo($this->min_age, $this->max_age);
            });
            $grid->column('cur_type', '招聘类型')->display(function () {
                if ($this->cur_type == JobpositionModel::TYPE_DATE) {
                    return "到期时间{$this->expiration_date}";
                }
                if ($this->cur_type == JobpositionModel::TYPE_NUMBER) {
                    return "招聘人数{$this->expected_num}";
                }
                return '暂无';
            });
            $grid->column('tags')->display(function ($tags) {
                if (!$tags) return '';
                return implode('|', $tags);
            });
            $grid->column('label', '标签')->using(JobpositionModel::LABEL_LIST);
            $grid->column('title_tag', '标题标签')->using(JobpositionModel::TITLE_TAG);
            $grid->column('data', '招聘时段')->display(function () {

                if (
                    empty($this->selection_date_start) && empty($this->selection_date_end)
                    && empty($this->work_time_start) && empty($this->work_time_end)
                ) {
                    return '全时段';
                }
                $html1 = '';
                $html2 = '';
                if ($this->selection_date_start && $this->selection_date_end) {
                    $html1 .= "{$this->selection_date_start} - {$this->selection_date_end}";
                } else if (empty($this->selection_date_start) && $this->selection_date_end) {
                    $html1 .= "到{$this->selection_date_end}结束";
                } else if (empty($this->selection_date_end) && $this->selection_date_start) {
                    $html1 .= "从{$this->selection_date_start}开始";
                }
                if ($this->work_time_start && $this->work_time_end) {
                    $html2 .= "{$this->work_time_start} - {$this->work_time_end}";
                } else if (empty($this->work_time_start) && $this->work_time_end) {
                    $html2 .= "到{$this->work_time_end}结束";
                } else if (empty($this->work_time_end) && $this->work_time_start) {
                    $html2 .= "从{$this->work_time_start}开始";
                }
                return " $html1<br> $html2";
            });
            $grid->column('created_at', '发布时间')->sortable();
            $grid->column('updated_at')->sortable();
            //            $grid->column('experience_requirement');
            //            $grid->column('job_description');
            //            $grid->column('work_location');

            //            $grid->column('contact_type')->using(JobpositionModel::CONTACT_TYPE_LIST);


            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $url = admin_url("sign-up?job_position_id=$this->id");
                $actions->append("<a href='" . $url . "' class='btn btn-success btn-sm'>报名列表</a>");
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $url = admin_url("chat?job_position_id=$this->id");
                $actions->append("<a href='{$url}' class='btn btn-sm' style='margin-left:10px;'>客服</a>");
            });

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $category = CategoryModel::query()->where('cur_status', 1)->pluck('name', 'id')->toArray() ?? [];
                $selector->selectOne('categories.id', '分类', $category);
                $selector->selectOne('cur_sss', '状态', JobpositionModel::STATUS_LIST, function ($query, $value) {
                    $query->where('cur_status', $value);
                });
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->expand();
                $filter->panel();
                $filter->equal('id')->width(2);
                $filter->like('position_name')->width(2);
                $filter->equal('company.id', '公司')->select(Tenancy::selectLis())->width(2);
            });
            $grid->fixColumns(0, -1);
            // 禁用过滤器按钮
            $grid->disableFilterButton();
            //边框模式
            //            $grid->withBorder();
            //横向滚动条
            $grid->scrollbarX();
            // 禁用批量删除按钮
            $grid->disableBatchDelete();
            // 禁用显示按钮
            //            $grid->disableViewButton();
            $grid->disableRowSelector();
            $grid->disableDeleteButton();
            // 启用表格异步渲染功能
            //            $grid->async();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Jobposition(['categories', 'contactPhone', 'contactQq', 'contactWechat', 'contactDingtalk', 'platforms', 'company']), function (Form $form) {
            // 第一列占据1/2的页面宽度
            $category = CategoryModel::query()->where('cur_status', 1)->pluck('name', 'id')->toArray() ?? [];
            $platform = PlatformModel::query()->where('cur_status', 1)->pluck('name', 'id')->toArray() ?? [];
            $form->tab('商家端提交信息', function (Form $form) {
                $isEditing = $form->isEditing();
                $info = '<i class="fa fa-exclamation-circle"></i>商家端提交信息';
                $form->html(Alert::make($info)->info());
                $form->select('company_id', '企业')->options(Tenancy::selectLis());
                $form->text('position_name');
                $form->text('salary')->required();
                $form->select('salary_type')->options(JobpositionModel::SALARY_TYPE_LIST)->required();
                $form->distpickerNationwide(['region_province', 'region_city', 'region_region'], '招聘区域');
                $form->textarea('job_description')->rows(4)->required();
                $form->timeRangeC('selection_date_start', 'selection_date_end', '招聘日期')->options([
                    'format' => 'YYYY-MM-DD',
                ]);
                $form->timeRangeC('work_time_start', 'work_time_end', '招聘时段');
                $info = '<i class="fa fa-exclamation-circle"></i>请设置聊天打招呼语，推荐联系方式 ';
                $form->html(Alert::make($info)->info());
                $form->textarea('greeting_message')->rows(3)->required();
                $info = '<i class="fa fa-exclamation-circle"></i>请设置联系方式 ';
                $form->html(Alert::make($info)->info());
                //                $form->radio('restrict_scene', '每个联系方式人数')->options([1 => '不限制', 2 => '限制'])->required()->value(1);
                $form->radio('contact_genre', '联系方式推荐方案')->options(JobpositionModel::CONTACT_GENRE_LIST)->required()->default(JobpositionModel::CONTACT_GENRE_ORDER);
                $form->radio('contact_type')->options(JobpositionModel::CONTACT_TYPE_LIST)->required()
                    ->when(JobpositionModel::CONTACT_MOBILE, function (Form $form) use ($isEditing) {
                        $form->hasMany('contactPhone', '手机号', function (Form\NestedForm $form) use ($isEditing) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(2);
                            $form->text('phone_number')->default('')->width(4);
                            $form->number('number', '最大报名数')->default('')->width(2);
                            if ($isEditing) {
                                $form->text('recruit_num', '报名人数')->width(2)->disable();
                            }
                        })->useTable()->width(10);
                    })->when(JobpositionModel::CONTACT_QQ, function (Form $form) use ($isEditing) {
                        $form->hasMany('contactQq', 'QQ', function (Form\NestedForm $form) use ($isEditing) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(1);
                            $form->text('qq_number')->width(4);
                            $form->image('qq_qr_code')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(3);
                            $form->number('number', '最大报名数')->default('')->width(2);
                            if ($isEditing) {
                                $form->text('recruit_num', '报名人数')->width(2)->disable();
                            }
                        })->useTable()->width(10);
                    })->when(JobpositionModel::CONTACT_WECHAT, function (Form $form) use ($isEditing) {
                        $form->hasMany('contactWechat', '微信', function (Form\NestedForm $form) use ($isEditing) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(1);
                            $form->text('wechat_number')->width(4);
                            $form->image('wechat_qr_code')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(3);
                            $form->number('number', '最大报名数')->default('')->width(4);
                            if ($isEditing) {
                                $form->text('recruit_num', '报名人数')->width(2)->disable();
                            }
                        })->useTable()->width(10);
                    })->when(JobpositionModel::CONTACT_DINGTALK, function (Form $form) use ($isEditing) {
                        $form->hasMany('contactDingtalk', '钉钉', function (Form\NestedForm $form) use ($isEditing) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(1);
                            $form->text('dingtalk_number', '钉钉号')->width(4);
                            $form->image('dingtalk_qr_code', '钉钉二维码')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(3);
                            $form->number('number', '最大报名数')->default('')->width(4);
                            if ($isEditing) {
                                $form->text('recruit_num', '报名人数')->width(2)->disable();
                            }
                        })->useTable()->width(10);
                    });
            });

            $form->tab('补充更多职位细节', function (Form $form) use ($category, $platform) {
                $info = '<i class="fa fa-exclamation-circle"></i>补充更多位置细节';
                $form->html(Alert::make($info)->info());
                $form->checkbox('platforms', '发布平台')->options($platform)
                    ->customFormat(function ($v) {
                        if (!$v) return [];
                        return array_column($v, 'id');
                    })->required();
                $form->radio('gender_requirement')->options(JobpositionModel::GENDER_LIST)->required()->default(JobpositionModel::DELETED_UNLIMITED);
                $form->radio('work_experience', '工作经验')->options(JobpositionModel::WORK_EXPERIENCE_LIST)->required()->default(0);
                $form->number('min_age');
                $form->number('max_age');
                $form->textarea('experience_requirement')->rows(4)->required();
                $form->radio('cur_type')->options(JobpositionModel::TYPE_LIST)->required()
                    ->when(JobpositionModel::TYPE_DATE, function (Form $form) {
                        $form->datetime('expiration_date');
                    })->when(JobpositionModel::TYPE_NUMBER, function (Form $form) {
                        $form->number('expected_num');
                    });
                $form->textarea('contact_message', '联系内容')->rules('max:255')->rows(3)->required();
                //                $form->textarea('response_message')->rows(3)->required();
                $form->checkbox('categories', '分类')->options($category)
                    ->customFormat(function ($v) {
                        if (!$v) return [];
                        return array_column($v, 'id');
                    });
                $form->tags('tags');
                $form->select('label', '标签')->options(JobpositionModel::LABEL_LIST);
                $form->select('title_tag', '标题标签')->options(JobpositionModel::TITLE_TAG);
                $info = '<i class="fa fa-exclamation-circle"></i>职位状态';
                $form->html(Alert::make($info)->info());
                $list = JobpositionModel::STATUS_LIST;
                $form->radio('cur_status', '状态')->options($list)->required();
            });
            $form->hidden('category_sort_1')->default(0);
            $form->hidden('category_sort_2')->default(0);
            $form->hidden('category_sort_3')->default(0);
            $form->hidden('category_sort_4')->default(0);
            $form->hidden('category_sort_5')->default(0);
            $form->hidden('category_sort_6')->default(0);
            $form->display('created_at');
            $form->display('updated_at');
            $form->saving(function (Form $form) {
                $distpicker_nationwide = $form->input('distpicker_nationwide');
                if ($distpicker_nationwide == 1) {
                    $form->region_province = '';
                    $form->region_city = '';
                    $form->region_region = '';
                }
                $region_province = $form->input('region_province');
                $region_city = $form->input('region_city');
                $region_region = $form->input('region_region');
                if ($region_province || $region_city || $region_region) {
                    if (!$region_province || !$region_city || !$region_region) {
                        return $form->response()->error('请填写详细地址~');
                    }
                }
                if (!empty($form->input('company_id'))) {
                    if (!$form->selection_date_start) {
                        $form->selection_date_start = null;
                    }
                    if (!$form->selection_date_end) {
                        $form->selection_date_end = null;
                    }
                    if (!$form->work_time_start) {
                        $form->work_time_start = null;
                    }
                    if (!$form->work_time_end) {
                        $form->work_time_end = null;
                    } else {
                        $form->work_time_end = $form->work_time_end . ":59";
                    }
                    return $this;
                }
            });
            $form->disableViewButton();
            $form->disableListButton();
            $form->disableDeleteButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();

            $form->saved(function (Form $form, $result) {
                // 自增ID
                $company = CompanyModel::where('id', $form->company_id)->first();
                $newId = $result;
                $wechatIm = new WechatService;
                $name = empty($company->contact_person_name) ? $company->company_name : $company->contact_person_name;
                $head = empty($company->contact_person_avatar) ? $company->logoUrl() : $company->contact_person_avatar;

                if ($form->isCreating()) {
                    try {
                        $wechatIm->create('job_' . $newId, $name,  $head);
                    } finally {
                    }
                    JobpositionModel::query()->where("id", $newId)->update(["is_im" => 1]);
                }
                $content = $form->position_name . $form->salary  . '/' . JobpositionModel::SALARY_TYPE_LIST[$form->salary_type];
                $wechatIm->attribute('job_' . $newId,  $name,  $head, $content);
            });
        });
    }

    public function show($id, Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['show'] ?? trans('admin.show'))
            ->body($this->detail($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new JobPosition(['company']), function (Show $show) use ($id) {

            //            $show->field('id');
            $show->field('company', '企业信息')->as(function ($value) {
                return $value['cur_type'] == CompanyModel::TYPE_PERSON ? $value['contact_person_name'] : $value['company_name'];
            });
            $show->field('region', '招聘区域')->as(function () {
                return $this->regionInfo();
            });
            $show->field('position_name');
            $show->field('selection_date_start', '招聘日期')->as(function ($value) {
                return "{$value} {$this->selection_date_end}";
            });
            $show->field('work_time_start', '招聘时间')->as(function ($value) {
                return "{$value} {$this->work_time_end}";
            });
            $show->field('salary')->as(function ($salary) {
                $salary_type = JobpositionModel::SALARY_TYPE_LIST[$this->salary_type] ?? '';
                return "{$salary} /{$salary_type}";
            });
            //            $show->field('tags')->explode('|')->label();
            //            $show->field('label', '标签')->using(JobpositionModel::LABEL_LIST);
            //            $show->field('title_tag', '标题标签')->using(JobpositionModel::TITLE_TAG);
            //            $show->field('gender_requirement')->using(JobpositionModel::GENDER_LIST);
            //            $show->field('min_age');
            //            $show->field('max_age');
            //            $show->field('experience_requirement');
            $show->field('job_description')->unescape();
            //            $show->field('expected_num');
            $show->field('greeting_message')->unescape();
            //            $show->field('response_message');
            //            $show->field('work_experience', '工作经验')->using(JobpositionModel::WORK_EXPERIENCE_LIST);
            //            $show->field('cur_type')->using(JobpositionModel::TYPE_LIST);
            //            $show->field('expiration_date');
            $show->field('created_at');
            $show->field('contact_type')->using(JobpositionModel::CONTACT_TYPE_LIST);
            $show->html(function () {
                $card = new Table();
                $rows = [];
                $header = [];
                if ($this->contact_type == JobpositionModel::CONTACT_MOBILE) {
                    $header = ['手机号'];
                    foreach ($this->contactPhone as $item) {
                        $rows[] = [
                            $item->phone_number,
                            //                            $item->number,
                            //                            $item->recruit_num,
                        ];
                    }
                }
                if ($this->contact_type == JobpositionModel::CONTACT_QQ) {
                    $header = ['QQ号码', '二维码'];
                    foreach ($this->contactQq as $item) {
                        $rows[] = [
                            $item->qq_number,
                            "<image src='$item->qq_qr_code' style='width: 150px'>",
                            //                            $item->number,
                            //                            $item->recruit_num,
                        ];
                    }
                }
                if ($this->contact_type == JobpositionModel::CONTACT_WECHAT) {
                    $header = ['微信号', '二维码'];
                    foreach ($this->contactWechat as $item) {
                        $rows[] = [
                            $item->wechat_number,
                            "<image src='$item->wechat_qr_code' style='width: 150px'>",
                            //                            $item->number,
                            //                            $item->recruit_num,
                        ];
                    }
                }

                if ($this->contact_type == JobpositionModel::CONTACT_DINGTALK) {
                    $header = ['钉钉号', '二维码'];
                    foreach ($this->contactDingtalk as $item) {
                        $rows[] = [
                            $item->dingtalk_number,
                            "<image src='$item->dingtalk_qr_code' style='width: 150px'>",
                            //                            $item->number,
                            //                            $item->recruit_num,
                        ];
                    }
                }
                if ($header) {
                    $card->setHeaders($header)->setRows($rows)->withBorder();
                    return "<div class='col-sm-8 offset-sm-2' style='padding:10px 10px 20px 5px'>$card</div>";
                } else {
                    return "<div class='col-sm-8 offset-sm-2' style='padding:10px 10px 0'>暂无联系方式</div>";
                }
            });
            $show->field('cur_status')->using(JobpositionModel::STATUS_LIST)->dot([
                1 => '#266EFF',
                2 => '#1B1F26',
                3 => '#FF6600',
                4 => '#FF4C4C',
            ]);
            if ($show->model()->cur_status == JobpositionModel::STATUS_CHECK_AWAIT) {
                $show->html($this->formCheck($id));
            }
            $show->panel()
                ->tools(function ($tools) {
                    $tools->disableEdit();
                    $tools->disableList();
                    $tools->disableDelete();
                    // 显示快捷编辑按钮
                    //                    $tools->showQuickEdit();
                });
        });
    }

    protected function formCheck($job_position_id)
    {
        return Form::make('', function (Form $form) use ($job_position_id) {
            $form->action(admin_url('job-position-check'));
            $form->title('驳回提交');
            $form->textarea('opinion', '审核意见');
            $form->hidden('job_position_id')->value($job_position_id);
            $form->disableViewButton();
            $form->disableListButton();
            $form->disableDeleteButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
        });
    }

    public function jobPositionCheck(Request $request)
    {
        $job_position_id = $request->get('job_position_id');
        $opinion = $request->get('opinion');
        $info = JobpositionModel::query()->find($job_position_id);
        if (!$info) {
            throw new ErrorException('职位信息不存在');
        }
        if ($info->cur_status != JobpositionModel::STATUS_CHECK_AWAIT) {
            throw new ErrorException('该职位无需审核');
        }
        $info->update([
            'cur_status' => JobpositionModel::STATUS_AWAIT_REJECT,
        ]);
        JobPositionCheckModel::query()->create([
            'job_position_id' => $job_position_id,
            'opinion' => $opinion ?? ''
        ]);
        return JsonResponse::make()->success('审核完成')->refresh();
    }
}
